from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
import time
import random

duration_min = 10
duration_max = 20

search_term_file = open('search_terms.txt', 'r')
search_terms = []
for term in search_term_file.readlines():
  search_terms.append(term)
search_term_file.close()

email_addr = "user"
email_pass = "password"

driver = webdriver.Firefox()
driver.get("http://www.google.com")

inputElement = driver.find_element_by_id("gbi4t")
inputElement.click()

"""
time.sleep(4)
email = driver.find_element_by_id("Email")
email.send_keys(email_addr)
password = driver.find_element_by_id("Passwd")
password.send_keys(email_pass)
sign_in = driver.find_element_by_id("signIn")
sign_in.click()
"""

time.sleep(4)
driver.get("http://www.google.com")

search = driver.find_element_by_id("gbqfq")
search.send_keys(search_terms[random.randrange(len(search_terms))])
search.submit()
# Needs something to combine terms from the list.  Modify later.
time.sleep(4)

def find_clickable():
  clickable = []
  elements = driver.find_elements_by_xpath("//a")
  for i in elements:
    if i.text != email_addr and len(i.text) > 20:
      clickable.append(i)
  return clickable

def ordered_click(number):
  for i in range(number):
    try:
      clickable = find_clickable()
      clickable.pop(0)
      clickable[i].click()
      time.sleep(random.randrange(duration_min, duration_max))
      driver.back()
    except IndexError:
      break

def random_click(number):
  for i in range(number):
    pos = random.randrange(len(clickable))
    try:
      clickable = find_clickable()
      clickable.pop(0)
      clickable[pos].click()
      time.sleep(random.randrange(duration_min, duration_max))
      driver.back()
    except IndexError:
      pass

ordered_click(3)
